package student.productions;

import java.util.Collections;
import java.util.Random;


public class Update extends MutableNode {
	//invariant for children: contains exactly two Terms

	/**
	 * Constructor: creates an instance of Update of form mem [ Term ] := Term.
	 * @param t1 this Update's first Term, parameter of mem.
	 * @param t2 this Update's second Term, the value mem [ Term ] is set to.
	 */
	public Update(Term t1, Term t2) {
		if(t1 != null && t2 != null){
			children.add(t1);
			children.add(t2);
		}
		else
			throw new IllegalArgumentException("Neither of the Term children of an Update can be null.");
	}

	@Override
	public void prettyPrint(StringBuffer sb) {
		sb.append("mem[");
		children.get(0).prettyPrint(sb);
		sb.deleteCharAt(sb.length() - 1);//removes the space before the ]
		sb.append("] := ");
		children.get(1).prettyPrint(sb);
	}

	@Override
	public void mutate(Program genome) {
		StringBuffer sb = new StringBuffer();
		prettyPrint(sb);
		sb.append("was changed to ");
		Random rnd = new Random();
		int child = rnd.nextInt(2);
		int mutationType = rnd.nextInt(3);
		if(mutationType <= 1)
			children.set(child, AbstractNode.generateTerm(genome, children.get(child)));
		else
			Collections.reverse(children);
		prettyPrint(sb);
		System.out.println(sb);
	}

	@Override
	public Node duplicate() {
		Term t1child= (Term)children.get(0).duplicate();
		Term t2child= (Term)children.get(1).duplicate();
		return new Update(t1child, t2child);
	}
}
